package com.sxdx.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sxdx.entity.Labinfo;
import com.sxdx.entity.Laboratory;
import com.sxdx.entity.Mydate;
import com.sxdx.entity.Orderinfo;
import com.sxdx.entity.Serialcode;
import com.sxdx.entity.Teacher;
import com.sxdx.service.ExcelService;
import com.sxdx.service.LabInfoService;
import com.sxdx.service.LabService;
import com.sxdx.service.MydateService;
import com.sxdx.service.OrderinfoService;
import com.sxdx.service.SerialcodeService;
import com.sxdx.service.TeacherService;
import com.sxdx.util.DateUtil;
import com.sxdx.util.Pager;

@SuppressWarnings("all")
@Controller
public class BaseAction extends ActionSupport{
	private static Logger logger = LogManager.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());
	
	private HttpServletResponse response;
	private HttpServletRequest request;
	private FileOutputStream out;
	private InputStream inputStream;
	private String fileName;
	
	private String url;
	private String message;
	private String date;
	private String number;
	
	private String username;
	private String password;
	private String repassword;
	private String newpassword;
	private String name;
	private String tele;
	private String dept;
	private String regcode;
	
	private	String id;
	private String rows;
	private String cols;
	
	private String course;
	private String clsname;
	private String labid;
	private String[] labids;
	private String labName;
	private String labContain;
	private String reserve;
	private String type;
	private String week;
	private String[] weektype;
	private String dayofweek;
	
	private List<Serialcode> codelist;
	private List<Laboratory> lablist;
	private List<Labinfo> labinfolist;
	private List<Orderinfo> orderinfolist;
	private List<Teacher> teacherlist;
	
	
	private Pager pager;
	
	@Resource(name="teacherService")
	private TeacherService teacherService;
	@Resource(name="serialcodeService")
	private SerialcodeService serialcodeService;
	@Resource(name="orderinfoService")
	private OrderinfoService orderinfoService;
	@Resource(name="labService")
	private LabService labService;
	@Resource(name="labInfoService")
	private LabInfoService labInfoService;
	@Resource(name="mydateService")
	private MydateService mydateService;
	@Resource(name="excelService")
	private ExcelService excelService;
	
	/******************************************Excel导出模块******************************************************/
	public InputStream getInputStream() throws FileNotFoundException{
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		List<Orderinfo> l = excelService.findorder(name,Integer.parseInt(week)-1, labids);
		try {
			fileName = new String(("第"+week+"周.xls").getBytes("gb2312"), "iso8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			out = new FileOutputStream("C://Users//Zyl//Desktop//第"+week+"周.xls");
		} catch (FileNotFoundException e) {
			e.getStackTrace();
		}
		excelService.expexcel((FileOutputStream) out, "第"+week+"周", l);
		return new FileInputStream("C://Users//Zyl//Desktop//第"+week+"周.xls");
	}
	
	/******************************************预约模块******************************************************/
	public String closeOrder(){
		labInfoService.changereserveclose(Integer.parseInt(labid));
		labService.changereserveclose(Integer.parseInt(labid));
		message = "成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	public String openOrder(){
		labInfoService.changereserveopen(Integer.parseInt(labid));
		labService.changereserveopen(Integer.parseInt(labid));
		message = "成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	public String orderInfo(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		orderinfolist = orderinfoService.orderinfo(Integer.parseInt(week)-1);
		url = "jsp/order/info.jsp";
		return SUCCESS;
	}
	
	public String deleteOrder(){
		List<Orderinfo> l =orderinfoService.finddeleteOrder(date, type, name);
		for (Orderinfo o : l) {
			Labinfo labinfo = labInfoService.getLabinfo(o.getOLabId(), date, type);
			labinfo.setLiMargin(labinfo.getLiMargin()+o.getOClassCount());
			labInfoService.updatelabinfo(labinfo);
			orderinfoService.deleteOrder(o);
		}
		message = "成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/**
	 * 批量预约
	 * @return
	 */
	public String pickOrder(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		for (int i = 0; i < weektype.length; i++) {
			List<Mydate> li = mydateService.getDate(Integer.parseInt(weektype[i]),Integer.parseInt(dayofweek));
			Mydate m = li.get(0);
			Labinfo l = labInfoService.getLabinfo(Integer.parseInt(labid),m.getDate(),type);
			Laboratory lab = labService.get(Integer.parseInt(labid));
			if(l.getLiReserve().equals("1")){
				if(l.getLiMargin()>=Integer.parseInt(number)){
					Orderinfo orderinfo = new Orderinfo();
					orderinfo.setODate(l.getLiODate());
					orderinfo.setOWeek(l.getLiOWeek());
					orderinfo.setODayofweek(DateUtil.getDayOfWeek(l.getLiODate()));
					orderinfo.setOType(Integer.parseInt(type));
					orderinfo.setOCourseName(course);
					orderinfo.setOTeacherName(name);
					orderinfo.setOClassCount(Integer.parseInt(number));
					orderinfo.setOClassName(clsname);
					orderinfo.setOLabName(lab.getLabName());
					orderinfo.setOLabId(Integer.parseInt(labid));
					orderinfoService.order(orderinfo);
					int margin = l.getLiMargin()-Integer.parseInt(number);
					l.setLiMargin(margin);
					labInfoService.updatelabinfo(l);
				}else{
					message = "其他周已录入;日期："+l.getLiODate()+"实验室名："+l.getLiLabName()+"第"+l.getLiOType()+"大节"+"当前余量不足";
					url="/WEB-INF/result/error.jsp";
					return ERROR;
				}
			}else{
				message = "当前不可预约";
				url="/WEB-INF/result/error.jsp";
				return ERROR;
			}
		}
		message = "成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	
	/**
	 * 预约
	 * @return
	 */
	public String insureOrder(){
		Labinfo l = labInfoService.getLabinfo(Integer.parseInt(labid),date,type);
		Laboratory lab = labService.get(Integer.parseInt(labid));
		if(l.getLiReserve().equals("1")){
			if(l.getLiMargin()>=Integer.parseInt(number)){
				Orderinfo orderinfo = new Orderinfo();
				orderinfo.setODate(l.getLiODate());
				orderinfo.setOWeek(l.getLiOWeek());
				orderinfo.setODayofweek(DateUtil.getDayOfWeek(l.getLiODate()));
				orderinfo.setOType(Integer.parseInt(type));
				orderinfo.setOCourseName(course);
				orderinfo.setOTeacherName(name);
				orderinfo.setOClassCount(Integer.parseInt(number));
				orderinfo.setOClassName(clsname);
				orderinfo.setOLabName(lab.getLabName());
				orderinfo.setOLabId(Integer.parseInt(labid));
				orderinfoService.order(orderinfo);
				int margin = l.getLiMargin()-Integer.parseInt(number);
				l.setLiMargin(margin);
				labInfoService.updatelabinfo(l);
				message = "成功";
				url = "/WEB-INF/result/success.jsp";
				return SUCCESS;
			}else{
				message = "日期："+l.getLiODate()+"实验室名："+l.getLiLabName()+"当前余量不足";
				url="/WEB-INF/result/error.jsp";
				return ERROR;
			}
		}else{
			message = "当前不可预约";
			url="/WEB-INF/result/error.jsp";
			return ERROR;
		}
	}
	/**
	 * 重置开学时间
	 * @return
	 */
	public String clearStartDate(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		mydateService.resetdate();
		orderinfoService.clearOrder();
		message = "重置成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/**
	 * 设置开学时间
	 * @return
	 */
	public String insureStartDate(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		mydateService.insureStartime(date, "139");
		message = "设置成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/******************************************实验室模块******************************************************/
	public String deleteLab(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		labInfoService.labinfodelete(labid);
		labService.deleteLab(labid);
		message = "删除实验室成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	
	/**
	 * 根据时间查询实验室
	 * @return
	 */
	public String labInfo(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		labinfolist = labInfoService.labInfo(date,type);
		url = "/jsp/lab/info.jsp";
		return SUCCESS;
	}
	
	/**
	 * 实验室状态
	 * @return
	 */
	public String laball(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		lablist = labService.labInfo();
		url = "/jsp/lab/labinfo.jsp";
		return SUCCESS;
	}
	/**
	 * 创建实验室
	 * @return
	 */
	public String createLab(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		Laboratory laboratory = new Laboratory();
		laboratory.setLabName(labName);
		laboratory.setLabContain(Integer.parseInt(labContain));
		laboratory.setReserve(reserve);
		labService.createLab(laboratory);
		labInfoService.createLabInfo(laboratory);
		message = "实验室创建成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/******************************************ajax模块******************************************************/
	public String ajaxlab(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		lablist = labService.labInfo();
		StringBuilder bu = new StringBuilder("[");
		for(Laboratory l : lablist){
			bu.append("{\"LId\":\""+l.getLId()+"\",");
			bu.append("\"labName\":\""+l.getLabName()+"\"},");
		}
		String json  = bu.substring(0, bu.lastIndexOf(",")) + "]";
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	public String ajaxgetmyweek(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		mydateService.getmyweek();
		List l = mydateService.getmyweek();
		StringBuilder sb = new StringBuilder("[");
		for (int i = 0; i < l.size(); i++) {
			int j = i+1;
			sb.append("{\"value\":\""+l.get(i)+"\",");
			sb.append("\"name\":\""+j+"\"},");
		}
		String json = sb.substring(0,sb.lastIndexOf(","))+"]";
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
	/******************************************用户管理模块******************************************************/
	
	public String editpassword(){
		Teacher teacher = teacherService.confirm(username, password);
		if(teacher!=null){
			if(newpassword.equals(repassword)){
				
			}
		}
		message = "成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}	
	
	/**
	 * 用户注册
	 * @return
	 */
	public String regist(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		if(!"".equals(password)&&null!=password){
			if(password.equals(repassword)){
			Teacher t = new Teacher();
			t.setUsername(username);
			t.setPassword(password);
			t.setName(name);
			t.setTele(tele);
			t.setDept(dept);
			t.setPermission("1");
			t.setLasttime(DateUtil.getCurrentDate("yyyy-MM-dd"));
			t.setCount(0);
			if(serialcodeService.setCodeFlag(regcode)){
				teacherService.save(t);
				ActionContext.getContext().getSession().put("teacher", t);
				url = "/main.jsp";
				return SUCCESS;
			}else{
				message = "注册码不正确";
				url="/WEB-INF/result/error.jsp";
				return ERROR;
			}
			}else{
				message = "密码不相等";
				System.out.println("密码不相等");
				return ERROR;
			}
		}else{
			message = "密码不能为空";
			System.out.println("密码null");
			url="/WEB-INF/result/error.jsp";
			return ERROR;
		}
	}
	public String registUser(){
		Teacher teacher = (Teacher) ActionContext.getContext().getSession().get("teacher");
		System.out.println(teacher.getPermission());
		if(!"".equals(password)&&null!=password){
			if(password.equals(repassword)){
			Teacher t = new Teacher();
			t.setUsername(username);
			t.setPassword(password);
			t.setName(name);
			t.setCourse(course);
			t.setPermission("1");
			t.setTele(tele);
			t.setDept(dept);
			t.setLasttime(DateUtil.getCurrentDate("yyyy-MM-dd"));
			t.setCount(0);
			teacherService.save(t);
			message = "成功";
			url = "/WEB-INF/result/success.jsp";
			return SUCCESS;
			}else{
				message = "密码不相等";
				System.out.println("密码不相等");
				return ERROR;
			}
		}else{
			message = "密码不能为空";
			System.out.println("密码null");
			url="/WEB-INF/result/error.jsp";
			return ERROR;
		}
	}
	public String deleteteacher(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		teacherService.delete(Integer.parseInt(id));
		message = "删除成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/**
	 * 查询教师信息
	 * @return
	 */
	public String teacherinfo(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		String hql = "from Teacher";
		if(pager == null){
			pager = new Pager();
			pager.setSize(8);
		}
		int page = pager.getOffset();
		int rows = pager.getSize();
		teacherlist = teacherService.info(hql,page, rows);
		pager.setDatas(teacherlist);
		pager.setTotalRecords(teacherService.findall());
		ActionContext.getContext().getSession().put("teacherlist", teacherlist);
		ActionContext.getContext().getSession().put("pager", pager);
		url = "/jsp/user/info.jsp";
		return SUCCESS;
	}
	/**
	 * 用户登录
	 * @return
	 */
	public String login(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		Teacher ac = (Teacher) ActionContext.getContext().getSession().get("teacher");
		if(ac==null){
			Teacher t = teacherService.confirm(username, password);
			if(t!=null){
				ActionContext.getContext().getSession().put("teacher", t);
				url = "/main.jsp";
				return SUCCESS;
			}else{
				message = "登录错误";
				url="/WEB-INF/result/error.jsp";
				return ERROR;
			}
		}else{
			message = "当前存在用户";
			url="/WEB-INF/result/error.jsp";
			return ERROR;
		}
	}
	/**
	 * 注销用户
	 */
	public String exit(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		ActionContext.getContext().getSession().remove("teacher");
		return SUCCESS;
	}
	
	/******************************************注册码模块******************************************************/
	/**
	 * 生成注册码
	 * @return
	 */
	public String keygen(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		serialcodeService.keygen(Integer.parseInt(rows), Integer.parseInt(cols));
		message = "注册码生成成功";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/**
	 * 清空注册码
	 * @return
	 */
	public String clearAll(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		serialcodeService.clsAllCode();
		message = "注册码清空";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	/**
	 * 清空使用过的注册码
	 * @return
	 */
	public String clearUsed(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		return SUCCESS;
	}
	/**
	 * 查询注册码
	 * @return
	 */
	public String findCode(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		String hql = "from Serialcode s order by s.SId desc";
		if(pager == null){
			pager = new Pager();
			pager.setSize(8);
		}
		int page = pager.getOffset();
		int rows = pager.getSize();
		codelist = serialcodeService.codeFind(hql, page, rows);
		pager.setDatas(codelist);
		pager.setTotalRecords(serialcodeService.findall());
		ActionContext.getContext().getSession().put("codelist", codelist);
		ActionContext.getContext().getSession().put("pager", pager);
		url = "/jsp/code/info.jsp";
		return SUCCESS;
	}
	/**
	 * 根据ID删除注册码
	 * @return
	 * 
	 */
	public String deleteCode(){
		logger.trace(Thread.currentThread().getStackTrace()[1].getMethodName());
		serialcodeService.deleteById(id);
		message = "注册码清空";
		url = "/WEB-INF/result/success.jsp";
		return SUCCESS;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRepassword() {
		return repassword;
	}
	public void setRepassword(String repassword) {
		this.repassword = repassword;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTele() {
		return tele;
	}
	public void setTele(String tele) {
		this.tele = tele;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
	public String getRegcode() {
		return regcode;
	}
	public void setRegcode(String regcode) {
		this.regcode = regcode;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getRows() {
		return rows;
	}
	public void setRows(String rows) {
		this.rows = rows;
	}
	public String getCols() {
		return cols;
	}
	public void setCols(String cols) {
		this.cols = cols;
	}
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	public String getClsname() {
		return clsname;
	}
	public void setClsname(String clsname) {
		this.clsname = clsname;
	}
	public String getLabid() {
		return labid;
	}
	public void setLabid(String labid) {
		this.labid = labid;
	}
	public String getLabContain() {
		return labContain;
	}
	public void setLabContain(String labContain) {
		this.labContain = labContain;
	}
	public String getReserve() {
		return reserve;
	}
	public void setReserve(String reserve) {
		this.reserve = reserve;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getWeek() {
		return week;
	}
	public void setWeek(String week) {
		this.week = week;
	}
	public String[] getWeektype() {
		return weektype;
	}
	public void setWeektype(String[] weektype) {
		this.weektype = weektype;
	}
	public String getDayofweek() {
		return dayofweek;
	}
	public void setDayofweek(String dayofweek) {
		this.dayofweek = dayofweek;
	}
	public List<Serialcode> getCodelist() {
		return codelist;
	}
	public void setCodelist(List<Serialcode> codelist) {
		this.codelist = codelist;
	}
	public List<Laboratory> getLablist() {
		return lablist;
	}
	public void setLablist(List<Laboratory> lablist) {
		this.lablist = lablist;
	}
	public List<Labinfo> getLabinfolist() {
		return labinfolist;
	}
	public void setLabinfolist(List<Labinfo> labinfolist) {
		this.labinfolist = labinfolist;
	}
	public List<Orderinfo> getOrderinfolist() {
		return orderinfolist;
	}
	public void setOrderinfolist(List<Orderinfo> orderinfolist) {
		this.orderinfolist = orderinfolist;
	}
	public List<Teacher> getTeacherlist() {
		return teacherlist;
	}
	public void setTeacherlist(List<Teacher> teacherlist) {
		this.teacherlist = teacherlist;
	}
	public Pager getPager() {
		return pager;
	}
	public void setPager(Pager pager) {
		this.pager = pager;
	}
	public LabService getLabService() {
		return labService;
	}
	public void setLabService(LabService labService) {
		this.labService = labService;
	}
	public String getLabName() {
		return labName;
	}
	public void setLabName(String labName) {
		this.labName = labName;
	}
	public String[] getLabids() {
		return labids;
	}
	public void setLabids(String[] labids) {
		this.labids = labids;
	}
	public FileOutputStream getOut() {
		return out;
	}
	public void setOut(FileOutputStream out) {
		this.out = out;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getNewpassword() {
		return newpassword;
	}

	public void setNewpassword(String newpassword) {
		this.newpassword = newpassword;
	}
}
